export default  class PoolManage extends cc.Component {
    static Instance = null;
    objectPools = {};
    /**
     * 
     * @returns 单例
     */
    static getInstance(){
        if(PoolManage.Instance == null){
            PoolManage.Instance = new PoolManage();
        }
        return PoolManage.Instance;
    }
    /**
     * 创建对象池
     * @param {*} poolName 
     * @param {*} prefab_ 
     * @param {*} initiaSize 
     */
    createObjectPool(poolName,prefab_,initiaSize){
        if(!this.objectPools[poolName]){
            let pool = new cc.NodePool();
            this.objectPools[poolName] = pool;

            if(initiaSize && initiaSize > 0){
                for (let i = 0; i < initiaSize; i++) {
                    let node = cc.instantiate(prefab_);
                    pool.put(node);
                    
                }
                return;
            }
            let node = cc.instantiate(prefab_);
            pool.put(node);
        }
    }
    /**
     * 获取对象
     * @param {*} poolName 
     * @returns 
     */
    getNode(poolName,prefab_){
        let pool = this.objectPools[poolName];
        if (pool) {
            let node_ = null;

            if( !pool.size() ){
                node_ = cc.instantiate(prefab_);
                pool.put(node_);
            }
            node_ = pool.get();
            node_.active = true;
            return node_;
        }
        return null,console.log('没有该对象池',poolName);
    }
    /**
     * 回收对象
     * @param {*} poolName 
     */
    putNode(poolName,node_){
        let pool = this.objectPools[poolName];
        if(pool){
            node_.active = false;
            pool.put(node_);
        }
    }
    /**
     * 自动填充对象池
     * @param {*} poolName 
     * @param {*} prefab_ 
     * @param {*} incrementSize 
     * @param {*} maxSize 
     */
    autoExpandpool(poolName,prefab_,incrementSize,maxSize){
        let pool = this.objectPools[poolName];
        if(!pool){
            this.createObjectPool(poolName,prefab_,incrementSize);
        } 
        else if(pool.size() < maxSize){
            for (let i = 0; i < incrementSize; i++) {
                let node = cc.instantiate(prefab_);
                pool.put(node);
            }
        }
    }
    /**
     * 清空对象池
     * @param {*} poolName 
     */
    clearPool(poolName){
        let pool = this.objectPools[poolName];
        if(pool){
            pool.clear();
            delete this.objectPools[poolName];
        }
    }
    /**
     * 获取所有对象池名字
     * @returns 
     */
    getAllPoolName(){
        return Object.keys(this.objectPools);
    }
    /**
     * 获取对象池大小
     * @param {*} poolName 
     * @returns 
     */
    getPoolSize(poolName){
        let pool = this.objectPools[poolName];
        if(pool){
            return pool.size();
        }
        return 0;
    }
    
}
